import { Component, OnInit, Injector, ViewChild, EventEmitter, Output } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator } from 'primeng/primeng';
import {
    ListDtoExtensionsItem,
    StockZT_RoomServiceProxy,
    StockZT_ReturnBillItemServiceProxy,
    Stock_ReturnToolItemListDto,
    StockZT_IntoBillItemServiceProxy,
    StockType,
    BillType,
    LabelValue,
    Stock_OutMarketBaseEditDto,
    StockZT_CancelBillServiceProxy,
    Stock_OutMarketItemListDto,
    Stock_IntoMarketItemForReturnListDto
} from '@shared/service-proxies/stock-service-proxies';
//import { DepartmentServiceProxy } from '@shared/service-proxies/stock-service-proxies';
import * as _ from 'lodash';
import { ModalDirective } from 'ngx-bootstrap';
import { UserDataPermissionServiceProxy, SessionServiceProxy } from '@shared/service-proxies/stock-service-proxies';
import { finalize } from 'rxjs/operators';
@Component({
    templateUrl: './create-or-edit-market-return-bill-item-modal.component.html',
    animations: [appModuleAnimation()],
    selector: 'createOrEditMarketReturnBillModal'
})
export class CreateOrEditMarketReturnBillModalComponent extends AppComponentBase implements OnInit {
    constructor(
        injector: Injector,
        private _billService: StockZT_ReturnBillItemServiceProxy,
        private _userDataPermissionService: UserDataPermissionServiceProxy,
        private _RoomServiceProxy: StockZT_RoomServiceProxy,
        private _intoBillItemService: StockZT_IntoBillItemServiceProxy,
        private _cancelBillService: StockZT_CancelBillServiceProxy,
    ) {
        super(injector);
    }
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Output() modalUpdate: EventEmitter<any> = new EventEmitter<any>();
    @Output() accountShow: EventEmitter<any> = new EventEmitter<any>();
    extensions: Array<ListDtoExtensionsItem>;
    detialExtensions: Array<ListDtoExtensionsItem>;
    f_currentDept; //当前部门
    selectedOutLearder; //审核领导
    optionOutLearder;
    optionInDept;
    selectedInDept; //调入单位
    optionInKeeper;
    selectedInKeeper; //调入单位保管员
    optionInAccounting;
    selectedInAccounting; //调度单位会计
    selectedBill: Array<Stock_ReturnToolItemListDto>;
    editBill: Stock_OutMarketItemListDto;
    billbase = new Stock_OutMarketBaseEditDto();
    f_TargetRoomNameOptions;
    miliOutBillList = new Array<Stock_OutMarketItemListDto>();
    f_MaterialTypeOptions;
    recipientsNatureOptions;
    userDataPermissions;
    selectedDepts;
    itemid;
    qccard;
    saving = false;
    closed = false;
    active = false;
    billid;
    roomOption;
    f_TargetLocationNameOption;
    f_Warehouse;
    f_StorageArea;


    marketReturnTitle;
    purchaseOption;
    selectedPurchaseType;
    isitemEdit = false;

    disabledPurchaseType = false;
    selectedToDept;
    disabledToDept;
    ngOnInit() {
        this._intoBillItemService.getPurchaseTypeOutByDataItem().subscribe(result1 => {
            this.purchaseOption = result1.map(e => {
                return {
                    label: e.label,
                    value: e
                };
            });
            if (result1.length > 0) {
                this.selectedPurchaseType = result1[0];
            }
        });
    }
    getStorage() {

    }
    getStorageInfo(index) {
        /* this.miliOutBillList[index].f_TargetLocationCode = this.f_StorageArea; */
    }

    show(id?: string, billitem?: Stock_OutMarketItemListDto): void {
        this.closed = false;
        this.active = true;
        this.billid = id;
        if (billitem != null || billitem != undefined) {
            this.itemid = billitem.id;
            this.editBill = billitem;
            //  billitem.f_Sort = 0;
            this.miliOutBillList.push(this.editBill);
            this.isitemEdit = true;
        } else {
            this.isitemEdit = false;
        }

        this._cancelBillService.getCancelMarketBaseForEdit(id, StockType.市采, BillType.退货).subscribe(result => {
            this.billbase = result;
            if (id == null || id == undefined || id == "") {
                this.disabledPurchaseType = false;
                this.marketReturnTitle = "创建市采物资退货单"
            } else {
                this.setSelectedPurchaseTypeByValue(this.billbase.f_PurchaseType);
                this.disabledPurchaseType = true;
                this.marketReturnTitle = "退货单编号：" + this.billbase.f_BillCode;
            }

            this.modal.show();
        });
    }

    changeInAccounting() {
        this._userDataPermissionService.getUserDataPermissions('Warehouses').subscribe(result => {
            // this.itemContextMenuItems = this.getContextMenuItems();
            this._RoomServiceProxy
                .getRoomList('工具库', result.items, this.selectedInDept.displayText, undefined, 1000, 0)
                .subscribe(result => {
                    this.f_TargetRoomNameOptions = result.items.map(e => {
                        return {
                            label: e.f_WarehouseName,
                            value: e
                        };
                    });
                });
        });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }

    getqccard(event) {
        this.qccard = event;
    }

    onHidden() {
        this.closed = true;
    }

    accountmodalshow() {
        this.close();

        let timer = setInterval(() => {
            if (this.closed) {
                this.accountShow.emit(this.selectedPurchaseType.value);
                clearInterval(timer);
            }
        }, 50);
    }

    delete() {
        if (!this.selectedBill) {
            this.notify.error('请先勾选对应的物料信息');
            return;
        }

        this.selectedBill.forEach(element => {
            let milioutbill = new Stock_OutMarketItemListDto();
            milioutbill = _.filter(this.miliOutBillList, { f_Sort: element.f_Sort })[0];
            _.remove(this.miliOutBillList, milioutbill);
        });

        this.selectedBill = null;
    }

    addAccoutInfo(event: Array<Stock_IntoMarketItemForReturnListDto>) {
        if (event) {
            event.forEach(element => {
                if (!this.miliOutBillList.find(e => element.f_MaterialCode == e.f_MaterialCode)) {
                    let milioutbill = new Stock_OutMarketItemListDto();
                    milioutbill.f_MaterialCode = element.f_MaterialCode;
                    milioutbill.f_MaterialName = element.f_MaterialName;
                    milioutbill.f_Unit = element.f_Unit;
                    milioutbill.f_WarehouseName = element.f_WarehouseName;
                    milioutbill.f_Location = element.f_Location;
                    milioutbill.f_PurchaseType = element.f_PurchaseType;
                    milioutbill.f_TradeMark = element.f_Trademark;
                    milioutbill.f_Station = element.f_Station;
                    milioutbill.f_TecCondition = element.f_TecCondition;
                    milioutbill.f_Specification = element.f_Specification;
                    milioutbill.f_Size = element.f_Size;
                    milioutbill.f_UnitPrice = element.f_UnitPrice;
                    /*  milioutbill.f_TargetRoomName = this.targetRoomName; // "天津火箭市采物资库";
                     milioutbill.f_TargetRoomCode = this.targetRoomCode; //"SC211-1"; */

                    milioutbill.f_Sort = this.miliOutBillList.length;
                    milioutbill.f_IntobillItemId = element.id;
                    milioutbill.f_RealUsable = element.remainQty;
                    milioutbill.f_TargetRoomName = element.f_Supplier;
                    milioutbill.f_AccountId = element.f_AccountId;


                    /*  milioutbill.f_InventSerialID = element.f_InventSerialID; */

                    this.miliOutBillList.push(milioutbill);
                }
            });
        }

        this.show(this.billid, undefined);
    }

    cancel(): void {
        this.close();
        this.miliOutBillList = new Array<Stock_OutMarketItemListDto>();
    }

    save(): void {
        this.saving = true;
        if (this.miliOutBillList.some(pg => pg.f_RealUsable < pg.f_Quantity)) {
            this.notify.error('退货数量不能大于实际可用！');
            this.saving = false;
            return;
        }
        if (this.miliOutBillList.some(element => element.f_Quantity == undefined || element.f_Quantity <= 0)) {
            this.notify.error(this.l('退货数量不正确！'));
            this.saving = false;
            return;
        }

        this.billbase.f_ToDept = '设备工装处';
        this.billbase.f_PurchaseType = this.selectedPurchaseType.value;
        //this.billbase.f_ToDeptId = 108;
        if (this.itemid == null || this.itemid == undefined || this.itemid == "") {
            this._billService.createOrUpdateReturnMarketBase(this.billbase).subscribe(result => {
                this.billbase.id = result;
                this._billService.createReturnMarketItems(this.miliOutBillList, result)
                    .pipe(
                        finalize(() => {
                            this.saving = false;
                        })
                    ).subscribe(() => {
                        this.notify.success(this.l('新增成功'));
                        this.modalSave.emit(this.billid);
                        this.billid = undefined;
                        this.itemid = undefined;
                        this.miliOutBillList = new Array<Stock_OutMarketItemListDto>();
                        this.close();
                    });
            });
        } else {
            this._billService.updateReturnMarketItems(this.itemid, this.miliOutBillList[0].f_Quantity)
                .pipe(
                    finalize(() => {
                        this.saving = false;
                    })
                )
                .subscribe(() => {
                    this.notify.success(this.l('更新成功'));
                    this.modalSave.emit(this.billid);
                    this.billid = undefined;
                    this.itemid = undefined;
                    this.miliOutBillList = new Array<Stock_OutMarketItemListDto>();
                    this.close();
                });
        }
    }

    purchaseChange() {
        if (this.miliOutBillList.length > 0) {
            this.message.confirm('更改市采类型会删除已添加的退库单详细信息，您确定吗？', isConfirmed => {
                if (isConfirmed) {
                    this.miliOutBillList = new Array<Stock_OutMarketItemListDto>();
                } else {
                    this.setSelectedPurchaseTypeByLabel(this.miliOutBillList[0].f_PurchaseType);
                }
            });
        }
    }

    //根据市采类型名称设置市采类型下拉列表
    setSelectedPurchaseTypeByLabel(label) {
        let t = new LabelValue();
        t.label = label;
        this.purchaseOption.forEach(element => {
            if (element.label == label) {
                t.value = element.value.value;
                this.selectedPurchaseType = t;
                return;
            }
        });
    }
    //根据市采类型值设置市采类型下拉列表
    setSelectedPurchaseTypeByValue(value) {
        let t = new LabelValue();
        t.value = value;
        this.purchaseOption.forEach(element => {
            if (element.value.value == value) {
                t.label = element.label;
                this.selectedPurchaseType = t;
                return;
            }
        });
    }
}
